using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;

using System.IO;
using System.IO.IsolatedStorage;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;

namespace UKVSTS
{
    public abstract class AddinConfig
    {
        private Hashtable m_Dictionary = new Hashtable();

        private String m_Name;

        protected AddinConfig (String name)
        {
            ValidateNameValid(name);
            m_Name = name;
        }

        protected Hashtable Properties
        {
            get { return m_Dictionary; }
        }

        protected bool Load()
        {
            bool success = false;
            try
            {
                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly())
                {
                    using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(m_Name, System.IO.FileMode.Open, isoFile))
                    {
                        //XmlSerializer xs = new XmlSerializer(typeof(Hashtable));
                        //m_Dictionary = xs.Deserialize(fs) as Hashtable;
                        BinaryFormatter bf = new BinaryFormatter();
                        m_Dictionary = (Hashtable) bf.Deserialize(fs);
                        
                        success = true;
                    }
                }
            }
            catch (Exception)
            {
                // If something has gone wrong, ensure that we wipe any 
                // config settings that may exist.
                //
                m_Dictionary = new Hashtable();
            }
            return success;
        }

        public void Save()
        {
            using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(m_Name, System.IO.FileMode.Create, isoFile))
                {
//                    XmlSerializer xs = new XmlSerializer(m_Dictionary.GetType());
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(fs, m_Dictionary);
                }
            }
        }

        private void ValidateNameValid(String name)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentException("cannot be null or empty", "name");
            }

            if (name.IndexOfAny(Path.GetInvalidFileNameChars ()) != -1)
            {
                throw new ArgumentException("contains invalid charaters", "name");
            }
        }
    }
}
